import Koa from "koa";
import { SqlUtil } from "../utils/page";
import { response } from "../utils/http";

// 校验接口的访问权限
export default function roleMiddleware(role: string) {
  return async (ctx: Koa.Context, next: Koa.Next) => {
    const userInfo = ctx.state.user;
    if (userInfo.user_name === "admin" && userInfo.user_id === 1) {
      await next();
    } else {
      const userRoeCode = await new SqlUtil()
        .Table("user")
        .Right("right join user_role on user.user_id = user_role.user_id")
        .Right("right join role on role.role_id = user_role.role_id")
        .Where(` FIND_IN_SET("${role}",role.role_code)`, role)
        .Where("user.user_id = ?", userInfo.user_id)
        .FindOne();

      if (userRoeCode || Number(userInfo.user_id) === 1) {
        await next();
      } else {
        ctx.body = response(
          500,
          null,
          "无访问权限，请联系管理员！" + `权限码：${role}`,
        );
      }
    }
  };
}
